package speed2010.andreza.vspeed.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.net.URL;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentFactory;
import org.dom4j.Node;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

/**
 * @author <a href="mailto:andreza.lba@gmail.com">Andreza Leite de Alencar</a>
 */
public final class XMLUtils {

	private XMLUtils() {
	}

	public static Document createDocument() {
		return DocumentFactory.getInstance().createDocument();
	}

	public static Document createDocument(final String encoding) {
		final Document vDocument = DocumentFactory.getInstance().createDocument();
		vDocument.setXMLEncoding(encoding);
		return vDocument;
	}

	public static Document createDocumentFromURL(final URL url) throws DocumentException {
		final SAXReader reader = new SAXReader();
		final Document document = reader.read(url);
		return document;
	}

	public static Document createDocumentFromString(final String xmlString) throws DocumentException {
		final SAXReader reader = new SAXReader();
		final Document document = reader.read(new StringReader(xmlString));
		return document;
	}

	public static Document createDocumentFromInputStream(final InputStream instream) throws DocumentException {
		final SAXReader reader = new SAXReader();
		final Document document = reader.read(instream);
		return document;
	}

	public static void printDocument(final Node doc) throws IOException {
		final OutputFormat format = OutputFormat.createPrettyPrint();
		final XMLWriter writer = new XMLWriter(System.out, format);
		writer.write(doc);
		writer.flush();
	}

	public static String getFormattedXML(final Node elem) {
		try {
			final StringWriter sw = new StringWriter();
			final String vXmlEncoding = elem.getDocument().getXMLEncoding();
			writeDocument(sw, elem, vXmlEncoding);
			return sw.toString().replace("&gt;", "&#62;").replace("&lt;", "&#60;").replace("&amp;", "&#38;");
		} catch (final IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static void writeDocument(final Writer writer, final Node doc, final String encoding) throws IOException {
		final OutputFormat format = OutputFormat.createPrettyPrint();
		format.setEncoding(encoding);
		final XMLWriter xmlWriter = new XMLWriter(writer, format);
		if ("ASCII".equals(format.getEncoding())) {
			xmlWriter.setMaximumAllowedCharacter(127);
		}
		xmlWriter.write(doc);
		xmlWriter.flush();
		xmlWriter.close();
	}

}
